package com.shanzhu.tourism.service;

import com.shanzhu.tourism.domain.Result;
import com.shanzhu.tourism.domain.Ticket;
import com.shanzhu.tourism.domain.TicketOrder;
import com.shanzhu.tourism.mapper.TicketMapper;
import com.shanzhu.tourism.mapper.TicketOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2025/03/28/14:52
 **/
@Service
@Slf4j
public class TicketService {

    @Autowired
    private TicketMapper ticketMapper;
    @Autowired
    private TicketOrderMapper ticketOrderMapper;


    public Result getTicketList(Ticket ticket) {
        try {
            List<Ticket> tickets = ticketMapper.selectList(ticket);
            return Result.success(tickets);
        } catch (Exception e) {
            return Result.fail("获取车票列表失败", e);
        }
    }

    @Transactional
    public Result bookTicket(TicketOrder order) {
        try {
            // 1. 检查票是否存在
            Ticket ticket = ticketMapper.selectById(order.getTicketId());
            if (ticket == null) {
                return Result.fail("车票不存在");
            }

            // 2. 检查余票
            if (ticket.getAvailableSeats() <= 0) {
                return Result.fail("已无余票");
            }

            // 3. 扣减余票
            int rows = ticketMapper.updateAvailableSeats(ticket.getTicketId(), -1);
            if (rows <= 0) {
                throw new RuntimeException("扣减余票失败");
            }

            // 4. 创建订单
            order.setAmount(ticket.getPrice());
            order.setOrderStatus(0); // 待支付
            ticketOrderMapper.insert(order);

            return Result.success("预订成功");
        } catch (Exception e) {
            return Result.fail("预订失败", e);
        }
    }
    public Ticket getTicketById(Long ticketId) {
        try {
            return ticketMapper.selectById(ticketId);
        } catch (Exception e) {
            log.error("获取车票详情失败", e);
            return null;
        }
    }
}
